local jwt = require "resty.jwt"
local json = require "cjson"
local jwt_key = "zf-class2024"

local headers = ngx.req.get_headers()
local auth_header = headers["auth"]
local token = string.gsub(auth_header, "bearer:", "")

local jwt_obj = jwt:verify(jwt_key, token)
local pb = require "protobuf"

--ngx.log(ngx.ERR,zf_common.tableToString(RestResponse))

local response
local tokenObject
if jwt_obj.valid then
	--ngx.say("jwt object is "..zf_common.tableToString(jwt_obj))
	if jwt_obj.verified then
		local payload = jwt_obj.payload
		local subStrBase64 = payload.sub
		local subStr = ngx.decode_base64(subStrBase64)
		
		local length = string.byte(subStr, 1) * 16777216 +
               string.byte(subStr, 2) * 65536 +
               string.byte(subStr, 3) * 256 +
               string.byte(subStr, 4)
        local actual_data = string.sub(subStr, 5, 4 + length)

        tokenObject = pb.decode("TokenObject",actual_data)
        local tokenObjectStr = json.encode(tokenObject)

        local base64TokenStr = ngx.encode_base64(tokenObjectStr)
        ngx.req.set_header("jwt_decode", "true")
        ngx.req.set_header("auth_data", base64TokenStr)
		--response = RestResponse.ok(tokenObject)
	else
		response = RestResponse.err("验证失败，失败原因为"..jwt_obj.reason)
	end

else
	response = RestResponse.err("jwt token verify faild, bacause "..jwt_obj.reason)
end

if response and response.code ~= 200 then
	ngx.header.content_type = "application/json"
	ngx.say(response:toJson())
else
	ngx.var.target = tokenObject.servId
end


